package help

import (
	"encoding/json"
	"log"
	"os"

	"gitee.com/baidugoogle/upload_file/upload_task/service_token"
	"gitee.com/baidugoogle/upload_file/upload_task/structs"
)

const (
	name           = "优视"
	appId          = "UeDYq4XIBNyOb4RrM2fZ306A"
	appKey         = "lse64Ym0IFBoWonYyYi2DWCCJmWbtIQH3U4JDw"
	configFilename = "config.json"
)

type JsonConfig struct {
	AppId  string `json:"appId"`
	AppKey string `json:"appKey"`

	URI            string `json:"uri"`
	Filename       string `json:"filename"`
	ResumeUploadId string `json:"resumeUploadId"`
	TaskCount      int    `json:"taskCount"`
	LoopCount      int    `json:"loopCount"`
	OneTaskThread  int    `json:"oneTaskThread"`
}

func NewJsonConfig() *JsonConfig {
	return &JsonConfig{
		AppId:          appId,
		AppKey:         appKey,
		URI:            "http://192.168.88.32:9780",
		Filename:       "demo.mp4",
		ResumeUploadId: "",
		TaskCount:      1,
		LoopCount:      1,
		OneTaskThread:  1,
	}
}

func (config *JsonConfig) Load() bool {
	if !structs.IsExists(configFilename) {
		data, _ := json.MarshalIndent(config, "", "  ")

		if err := os.WriteFile(configFilename, data, os.ModePerm); err != nil {
			log.Println(err)
		}
		log.Println("create default config.json")
		return false
	} else {
		if data, err := os.ReadFile(configFilename); err != nil {
			log.Println(err)
			return false
		} else if err = json.Unmarshal(data, config); err != nil {
			log.Println(err)
			return false
		}

		if data, err := json.MarshalIndent(config, "", "  "); err == nil {
			log.Println("config: ", string(data))

			if err := os.WriteFile(configFilename, data, os.ModePerm); err != nil {
				log.Println(err)
			}
		}
	}

	if len(config.Filename) > 0 && !structs.IsExists(config.Filename) {
		log.Printf("file not exist %v", config.Filename)
		return false
	}

	return true
}

func (config *JsonConfig) GetToken() string {
	if objectToken, e1 := service_token.NewTokenInfo(config.AppId, config.AppKey, "upload_file"); e1 != nil {
		panic(e1)
	} else if token, e2 := objectToken.String(); e2 != nil {
		panic(e2)
	} else {
		return token
	}
}
